var beginNum = 8; //初始化数据条数
var pageNum = 5; //分页条数
var viewNum = 8; //当前条数
var name, dateval, content, type, add_div, edit_div, title;
$(function() {
	document.getElementById("open").addEventListener('tap', function() {
		initParams();
		$("#name").val("");
		dateval.val("");
		content.val("");
		type.val("");
		title.html("新增待办事项");
		add_div.removeClass("mui-hidden");
		edit_div.addClass("mui-hidden");
		mui("#popover").popover("toggle");
	});

	//$("#add")[0]
	document.getElementById("add").addEventListener('tap', function() {
		initParams()
		var check = true;
		var ref = sun.createLink("/todo");
		mui(".mui-input-group input").each(function() {
			if(!this.value || trim(this.value) == "") {
				var label = this.previousElementSibling;
				mui.alert(label.innerText + "不允许为空");
				check = false;
				return false;
			}
		});
		if(check) {
			var newRef = ref.push({
				"name": $("#name").val(),
				"dateval": dateval.val(),
				"content": content.val(),
				"type": "未完",
				"userId": app.getUser().account
			});
			add_div.addClass("mui-hidden");
			//关闭modal
			mui("#popover").popover("toggle");
			mui.toast("添加成功~");
			//刷新界面
			initTodos();//初试化缓存
			getTodoList();//加载未完成列表
		}
	});
	var dataId;
	mui("#todolist").on("longtap", "li", function() {
		dataId = this.getAttribute("data-id");
		mui("#operation").popover("toggle");
	});

	$("#endli")[0].addEventListener("tap", function() {
		initParams();
		var ref = sun.createLink("/todo");
		var newRef = ref.child(dataId);
		newRef.update({
			"type": "已完"
		});
		//关闭modal
		mui("#operation").popover("toggle");
		edit_div.addClass("mui-hidden");
		mui.toast("修改成功~");
		initTodos();//初试化缓存
		getTodoList();//加载未完成列表
		getFinishList();//初始化已完成列表
	});

	mui(".todo").on("tap", "li", function() {
		var id = this.getAttribute("data-id");
		initParams()
		if(id) {
			$("#name").val($(this).find("#name_").text());
			$("#dateval").val($(this).find("#dateval_").text().replace(/"/g, ""));
			$("#content").val($(this).find("#content_").text());
			$("#type").val($(this).find("#type_").text());
			$("#name").attr("data-id", id);
			$("#title").html("编辑数据");
			add_div.addClass("mui-hidden");
			edit_div.removeClass("mui-hidden");
			mui("#popover").popover("toggle");
		}
	});

	$("#update")[0].addEventListener("tap", function() {
		var check = true;
		initParams()
		mui(".mui-input-group input").each(function() {
			if(!this.value || trim(this.value) == "") {
				var label = this.previousElementSibling;
				mui.alert(label.innerText + "不允许为空");
				check = false;
				return false;
			}
		});
		if(check) {
			initParams()
			var ref = sun.createLink("/todo");
			var newRef = ref.child($("#name").attr("data-id"));
			newRef.update({
				"name": $("#name").val(),
				"dateval": dateval.val(),
				"content": content.val(),
				"type": type.val()
			});
			//关闭modal
			mui("#popover").popover("toggle");
			edit_div.addClass("mui-hidden")
			mui.toast("修改成功~");
			initTodos();//初试化缓存
			getTodoList();//加载未完成列表
			getFinishList();//初始化已完成列表
		}
	});

	$("#del")[0].addEventListener("tap", function() {
		initParams();
		var ref = sun.createLink("/todo");
		var newRef = ref.child($("#name").attr("data-id"));
		newRef.remove();
		//关闭modal
		mui("#popover").popover("toggle");
		edit_div.addClass("mui-hidden");
		mui.toast("删除成功~");
		//刷新界面
		initTodos();//初试化缓存
		getTodoList();//加载未完成列表
		getFinishList();//初始化已完成列表
	});
});

/**
 * 初始化列表缓存
 */
function initTodos() {
	var ref = sun.createLink("/todo");
	var todos = [];
	var finishTodos = [];
	ref.on("value", function(snapshot) {
		var result = snapshot.val();
		mui.each(result, function(key, item) {
			if(item.userId == app.getUser().account) {
				var todo = {};
				todo = sun.cloneObj(item);
				todo.id = key;
				if (todo.type == "未完") {
					todos.push(todo);
				} else if(todo.type == "已完") {
					finishTodos.push(todo);
				}
			}
		});
		todos.sort(function(oa, ob) {
			var oDate1 = new Date(oa.dateval);
			var oDate2 = new Date(ob.dateval);
			if(oDate1.getTime() > oDate2.getTime()) {
				return -1;
			} else if(oDate1.getTime() < oDate2.getTime()) {
				return 1
			}
		});
		finishTodos.sort(function(oa, ob) {
			var oDate1 = new Date(oa.dateval);
			var oDate2 = new Date(ob.dateval);
			if(oDate1.getTime() > oDate2.getTime()) {
				return -1;
			} else if(oDate1.getTime() < oDate2.getTime()) {
				return 1
			}
		});
		localStorage.setItem("$todos", JSON.stringify(todos));
		localStorage.setItem("$finishtodos", JSON.stringify(finishTodos));
	});
}

/**
 * 初始化数据
 */
function initParams() {
	name = $("#name");
	dateval = $("#dateval");
	content = $("#content");
	type = $("#type");
	add_div = $("#add_div");
	edit_div = $("#edit_div");
	title = $("#title");
}

/**
 * 获得未完成的列表，未完成的数量不多，这里全部显示
 */
function getTodoList() {
	var $ul = $('#todolist').empty();
	var array = JSON.parse(localStorage.getItem('$todos'));
	for(var o in array) {
		$ul.append(getTodoData(array[o]));
	}
	if($ul.find('li').size() > 0 && $ul.is(':hidden')) $ul.show();
}
/**
 * 
 * <p>并且增加标记剩余天数</p>
 */
function getTodoData(data) {
	var id = data.id;
	var name = data.name;
	var content = data.content;
	var dateval = JSON.stringify(data.dateval);
	var type = "未完";
	var li = '<li class="mui-table-view-cell mui-collapse" data-id="' + id + '">';
	//li += '<span class="mui-badge mui-badge-danger mui-pull-right">未完</span>'; 右侧角标
	li += '<div id="name_">' + name + '</div>';
	li += '<p id="dateval_">' + dateval + '</p>';
	li += '<div id="content_" style="display:none">' + content + '</div>';
	li += '<div id="type_" style="display:none">' + type + '</div>';
	li += '</li>';
	return li;
}

/**
 * 初始化已完成的数据
 * @param {Object} begin 开始节点
 * @param {Object} end 结束节点
 * @param {Object} type 类型 如果不为null则不刷新缓存，拼接数据
 */
function getFinishList(begin, end, type) {
	if(!begin) begin = 0;
	if(!end) end = 8;
	if (!type) type = false;
	var $ul;
	if(type) {
		$ul = $('#finishList');
	} else {
		initTodos();
		$ul = $('#finishList').empty();
		viewNum = 8;
	}
	var array = JSON.parse(localStorage.getItem('$finishtodos'));
	var data = array.slice(begin, end);
	for(var o in data) {
		$ul.append(getFinishData(data[o]));
	}
	if($ul.find('li').size() > 0 && $ul.is(':hidden')) $ul.show();
}
function getFinishData(data) {
	var id = data.id;
	var name = data.name;
	var content = data.content;
	var dateval = JSON.stringify(data.dateval);
	var type = data.type;
	var li = '<li class="mui-table-view-cell mui-collapse" data-id="' + id + '">';
	li += '<div id="name_">' + name + '</div>';
	li += '<p id="dateval_">' + dateval + '</p>';
	li += '<div id="content_" style="display:none">' + content + '</div>';
	li += '<div id="type_" style="display:none">' + type + '</div>';
	li += '</li>';
	return li;
}

function trim(str) { //删除左右两端的空格
	return str.replace(/(^\s*)|(\s*$)/g, "");　　
}
/**
 * 下拉刷新具体业务实现
 */
function pulldownRefresh() {
	setTimeout(function() {
		//initList(0, 8, 0);
		mui('#refreshContainer').pullRefresh().endPulldownToRefresh(false); //判断是否拥有数据
	}, 1500);
}
var count = 0;
/**
 * 上拉加载具体业务实现
 */
function pullupRefresh() {
	setTimeout(function() {
		var todoArray = JSON.parse(localStorage.getItem("$finishtodos"));
		if(todoArray.length >= viewNum) {
			viewNum += 5;
			getFinishList(viewNum - 5, viewNum, true);
			mui('#refreshContainer').pullRefresh().endPullupToRefresh(false);
		} else {
			mui('#refreshContainer').pullRefresh().endPullupToRefresh(true); //参数为true代表没有更多数据了。
		}
	}, 1500);
}
//if(mui.os.plus) {
//	mui.plusReady(function() {
//		setTimeout(function() {
//			mui('#refreshContainer').pullRefresh().pullupLoading();
//		}, 1000);
//
//	});
//} else {
//	mui.ready(function() {
//		mui('#refreshContainer').pullRefresh().pullupLoading();
//	});
//}